package com.cy.dda.comm.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.cy.dda.comm.constant.Constants;
import com.cy.dda.comm.exception.MsgException;
import com.cy.dda.comm.utils.CommonUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * 前台用户拦截器
 *
 * @author: tanyilin
 * @create: 2018年10月29日 上午10:35:53
 */
@Slf4j
@Component
public class UserLoginInterceptor implements HandlerInterceptor{

	@Autowired
	private RedisTemplate redisTemplate;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 从请求头部获取token
		String token = request.getHeader(Constants.TOKEN);
		if(CommonUtils.isEmpty(token)) {
			throw new MsgException("未登录", -1000);
		}
		// 查询redis里是否有已登录用户的信息
		String key = Constants.USER_LOGIN_KEY.concat(token);
		Object obj = redisTemplate.opsForValue().get(key);
		if(CommonUtils.isEmpty(obj)) {
			throw new MsgException("登录已失效", -1000);
		}
		// 激活有效时间
		redisTemplate.expire(key, Constants.LOGIN_TIME, Constants.LOGIN_TIME_UNIT);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
	}
	
	
}
